﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Diagnostics;
using System.IO;

using NGE;
using NGE.Net;

namespace MH.Loader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        List<string> sfilename = new List<string>();
        List<string> sfilevers = new List<string>();

        WebClient webClient = new WebClient();
        string fn;
        string path = "http://mh.meibu.com/";
        bool next = false;

        int fileIndex = -1;
        string GetMD5(string fileName)
        {
            string hashMD5 = string.Empty;

            //检查文件是否存在，如果文件存在则进行计算，否则返回空值
            if (System.IO.File.Exists(fileName))
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    //计算文件的MD5值
                    System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
                    Byte[] buffer = calculator.ComputeHash(fs);
                    calculator.Clear();
                    //将字节数组转换成十六进制的字符串形式
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < buffer.Length; i++)
                    {
                        stringBuilder.Append(buffer[i].ToString("x2"));
                    }
                    hashMD5 = stringBuilder.ToString();
                }//关闭文件流

            }//结束计算

            return hashMD5;
        }
        void download(string name)
        {
            fn = name;
            if (fn == "fl.txt")
            {
                label1.Text = "与服务器连接中……";
            }
            else
            {
                label1.Text = "正在下载：" + fn;
            }
            string dir = Path.GetDirectoryName(fn);
            string dir2 = "";
            if (dir != string.Empty)
            {
                dir2 = dir.Replace("\\", "/");
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                dir += "\\";
                dir2 += "/";
            }
            fn = Path.GetFileName(fn);
            string src = path + dir2 + fn;
            if (fn == "fl.txt")
            {
                webClient.DownloadFileAsync(new Uri(src), "c:\\fl.txt");
            }
            else
            {
                webClient.DownloadFileAsync(new Uri(src), dir + fn);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //webClient.SetTimeout(3000);
            //webClient.

            button1.Enabled = false;

            

            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);

            download("fl.txt");
        }

        void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (fn == "fl.txt")
            {
                sfilename.Clear();
                sfilevers.Clear();
                string[] lines = File.ReadAllLines("c:\\" + fn);
                for (int i = 0; i < lines.Length; i++)
                {
                    sfilename.Add(lines[i++]);
                    sfilevers.Add(lines[i]);
                }
                if (sfilename.Count > 0)
                {
                    fileIndex = 0;
                }
                else
                {
                    return;
                }
            }
            do
            {
                next = false;
                if (fileIndex < sfilename.Count)
                {
                    //string fv = FileVersionInfo.GetVersionInfo(sfilename[fileIndex]).FileVersion;
                    string fv = GetMD5(sfilename[fileIndex]);
                    if (fv != sfilevers[fileIndex])
                    {
                        download(sfilename[fileIndex]);
                    }
                    else
                    {
                        next = true;
                    }
                    fileIndex++;
                }
                else
                {
                    System.IO.File.Delete("fl.inf");
                    button1.Enabled = true;
                    label1.Text = "更新完成";
                }
            }
            while (next);
        }

        void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            try
            {
                progressBar1.Value = (int)((double)e.BytesReceived / (double)e.TotalBytesToReceive * 100.0);
            }
            catch { }
        }

        private void button1_Click(object sender, EventArgs e)
        {

            ProcessStartInfo info = new ProcessStartInfo();             
            info.FileName = @"metalhunter.exe";              
            info.Arguments = "";              
            //info.WindowStyle = ProcessWindowStyle.Minimized;             
            Process pro = Process.Start(info);
            Application.Exit();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //if (webClient.IsTimeout)
            //{
            //    timer1.Enabled = false;
            //    MessageBox.Show("连接服务器超时，引起这种状况的原因可能是\n网络状况不好或者服务器没有开启。");
            //    Close();
            //}
        }
    }
}
